package com.xh.petdogexpert.expert.service.imp;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xh.petdogexpert.expert.dto.ArticlePush;
import com.xh.petdogexpert.expert.mapper.ArticlePushMapper;
import com.xh.petdogexpert.expert.service.IArticleService;
import com.xh.petdogexpert.user.dto.User;

@Service
public class ArticleServiceImp implements IArticleService {

	String APIKEY = "3ZSXaaGODOf03wPIsZVmT78y";
	String SECRETKEY = "OT9g4tVKXvuGDNma4RtrEcqzEHTBmBCl";

	@Autowired
	HttpSession session;
	@Autowired
	ArticlePushMapper articlePushMapper;

	public String pushToAndroid(Map article) throws PushClientException, PushServerException, JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		String articleContent = objectMapper.writeValueAsString(article);
		articleContent = articleContent.replace("\\", "");
		System.out.println("!!!!! " + articleContent);
		/*
		 * 1. 创建PushKeyPair 用于app的合法身份认证 apikey和secretKey可在应用详情中获取
		 */
		String apiKey = APIKEY;
		String secretKey = SECRETKEY;
		PushKeyPair pair = new PushKeyPair(apiKey, secretKey);

		// 2. 创建BaiduPushClient，访问SDK接口
		BaiduPushClient pushClient = new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);

		// 3. 注册YunLogHandler，获取本次请求的交互信息
		pushClient.setChannelLogHandler(new YunLogHandler() {
			@Override
			public void onHandle(YunLogEvent event) {
				System.out.println(event.getMessage());
			}
		});

		try {
			// 4. 设置请求参数，创建请求实例
			PushMsgToAllRequest request = new PushMsgToAllRequest().

					addMsgExpires(new Integer(3600)). // 设置消息的有效时间,单位秒,默认3600*5.
					addMessageType(1). // 设置消息类型,0表示透传消息,1表示通知,默认为0.
					addMessage(articleContent).addDeviceType(3); // 设置设备类型，deviceType
																	// => 1 for
																	// web, 2
																	// for pc,
																	// 3 for
																	// android,
																	// 4 for
																	// ios, 5
																	// for wp.
			// 5. 执行Http请求
			PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
			// 6. Http请求返回值解析
			System.out.println("msgId: " + response.getMsgId() + ",sendTime: " + response.getSendTime());
		} catch (PushClientException e) {
			// ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,
			// 'true' 表示抛出, 'false' 表示捕获。
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				e.printStackTrace();
			}
		} catch (PushServerException e) {
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				System.out.println(String.format("requestId: %d, errorCode: %d, errorMsg: %s", e.getRequestId(),
						e.getErrorCode(), e.getErrorMsg()));
			}
		}
		return "推送成功";
	}

	public boolean zan(Integer id) {
		int userId = ((User) (session.getAttribute("user"))).getId();
		if (articlePushMapper.zan(userId, id) > 0)
			return true;
		else
			return false;
	}

	public Integer getArticleZan(int articleId) {
		return articlePushMapper.getArticleZan(articleId);
	}

	public ArticlePush getArticleDetail(Integer id) {

		ArticlePush article = articlePushMapper.selectByPrimaryKey(id);
		if (session.getAttribute("user") == null) {
			article.setMyZan(false);
		} else {
			int userId = ((User) (session.getAttribute("user"))).getId();
			Integer zan = articlePushMapper.isZan(userId, id);
			if (zan > 0) {
				article.setMyZan(true);
			}
		}
		return article;
	}

	public List<ArticlePush> queryArticlePushs(ArticlePush articlePush, Integer pagenum, Integer pagesize) {
		PageHelper.startPage(pagenum, pagesize);
		List<ArticlePush> queryArticlePushs = articlePushMapper.queryArticlePushs(articlePush);
		for (ArticlePush a : queryArticlePushs) {
			a.setZanCount(getArticleZan(a.getId()));
		}
		return queryArticlePushs;
	}
}
